package com.realbrand.net.realbrandpay.ui.activity.wallet.personer;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.inter.IChangePhoto;
import com.realbrand.net.realbrandpay.ui.activity.SetPersonImageActivity;
import com.realbrand.net.realbrandpay.ui.activity.login.LoginActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.WalletActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.personer.adress.ManagerAdressActivity;
import com.realbrand.net.realbrandpay.untils.HttpRequest;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.util.L;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/7/10.
 */

public class AccountActivity extends BaseActivity {
    @BindView(R.id.account_toolbar)
    Toolbar accountToolbar;
    @BindView(R.id.account_linear_personMessage)
    LinearLayout accountLinearPersonMessage;
    @BindView(R.id.account_linear_boundPhone)
    LinearLayout accountLinearBoundPhone;
    @BindView(R.id.account_linear_boundPay)
    LinearLayout accountLinearBoundPay;
    @BindView(R.id.account_tv_userName)
    TextView accountTvUserName;
    @BindView(R.id.account_tv_UserMobile)
    TextView accountTvUserMobile;
    @BindView(R.id.account_cv_image)
    CircleImageView accountCvImage;
    @BindView(R.id.account_linear_photo)
    LinearLayout accountLinearPhoto;

    public static final int CHANGEPHOTO = 0x005;
    @BindView(R.id.boundpay_tv_boundPay)
    TextView boundpayTvBoundPay;
    @BindView(R.id.account_linear_address)
    LinearLayout accountLinearAddress;
    @BindView(R.id.account_linear_scan)
    LinearLayout accountLinearScan;
    @BindView(R.id.account_tv_userType)
    TextView accountTvUserType;
    private Bitmap bitmap;

    //用户名跟用户手机号码、图片地址
    String UserName;
    String UserMobile;
    String photoUrl;
    String userType;
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        accountToolbar.setTitle("");
        accountToolbar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(accountToolbar);
        accountToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(AccountActivity.this, WalletActivity.class));
                finish();
            }
        });
            sharedPreferences = getSharedPreferences("userMassage", MODE_PRIVATE);
            UserName = sharedPreferences.getString("account", "");
            UserMobile = sharedPreferences.getString("mobile", "");
            photoUrl = sharedPreferences.getString("avatar", "");
            userType = sharedPreferences.getString("userType", "");
            L.d(L.TAG, "图片地址" + photoUrl + "，用户手机号码" + UserMobile + ",用户名" + UserName);
            accountTvUserName.setText(UserName);
            accountTvUserMobile.setText(UserMobile);
            if (userType.equals("5")) {
                accountTvUserType.setText("会员");
            } else if (userType.equals("6")) {
                accountTvUserType.setText("服务员");
            }
            Picasso.with(this).load(photoUrl).memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into(accountCvImage);
        String wxName = sharedPreferences.getString("WXName", "");
        String alipayName = sharedPreferences.getString("alipayName", "");
        if ((!"".equals(wxName)) && (!"".equals(alipayName))) {
            boundpayTvBoundPay.setText("2种");
        } else if ("".equals(wxName) && "".equals(alipayName)) {
            boundpayTvBoundPay.setText("0种");
        } else {
            boundpayTvBoundPay.setText("1种");
        }
        setOnClick();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.account_activity;
    }

    @Override
    protected void onResume() {
        super.onResume();
        UserMobile = sharedPreferences.getString("mobile", "");
        accountTvUserMobile.setText(UserMobile);
        L.d(L.TAG, "onResume的手机号码" + UserMobile);
    }

    @Override
    protected void setOnClick() {
        accountLinearBoundPay.setOnClickListener(this);
        accountLinearBoundPhone.setOnClickListener(this);
        accountLinearPhoto.setOnClickListener(this);
        accountLinearAddress.setOnClickListener(this);
        accountLinearScan.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //绑定支付方式
            case R.id.account_linear_boundPay:
                Intent intent = new Intent(this, BoundPayActivity.class);
                intent.putExtra("usreName", UserName);
                startActivity(intent);
                finish();
                break;
            //绑定手机号码
            case R.id.account_linear_boundPhone:
                Intent intentMobile = new Intent(this, BoundPhoneActivity.class);
                intentMobile.putExtra("mobile", accountTvUserMobile.getText().toString());
                startActivity(intentMobile);
                break;
            //更换图像
            case R.id.account_linear_photo:
                Intent intentImage = new Intent(this, SetPersonImageActivity.class);
                intentImage.putExtra("urlPhoto", photoUrl);
                startActivityForResult(intentImage, CHANGEPHOTO);
                break;
            //地址
            case R.id.account_linear_address:
                Intent intentAdress = new Intent(this, ManagerAdressActivity.class);
                intentAdress.putExtra("AdressUser", UserName);
                startActivity(intentAdress);
                break;
            //开柜码
            case R.id.account_linear_scan:
                if (userType.equals("6")) {
                    Intent intentScan = new Intent(this, OpenScanActivity.class);
                    startActivity(intentScan);
                } else {
                    Static.toast(this, "该功能暂不开放");
                }
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CHANGEPHOTO:
                    bitmap = data.getParcelableExtra("bitmap");
                    Drawable drawable = new BitmapDrawable(bitmap);
                    accountCvImage.setImageDrawable(drawable);
                    //插入到数据库
                    changePhoto();
                    break;
            }
        }
    }

    private void changePhoto() {
        //将图片转成字符串
        String photo = Static.bitmapToString(bitmap);
        final JSONObject jsonObject = new JSONObject();
        L.d(L.TAG, "传过去的账户名" + UserName);
        String account = accountTvUserName.getText().toString();
        try {
            jsonObject.put("UserAccount", account);
            jsonObject.put("UserAvatar", photo);
            jsonObject.put("SOURCE", "AccountActivity");
            jsonObject.put("CREDENTIALS", "0");
            jsonObject.put("TERMINAL", "1");
            jsonObject.put("INDEX", Static.getDay());
            jsonObject.put("METHOD", "ChangeUserAvatar");
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonObject.toString());
            IChangePhoto changePhoto = HttpRequest.request_BASE_URL(IChangePhoto.class);
            Call<ResponseBody> call = changePhoto.changePhoto(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String result = response.body().string();
                        L.d(L.TAG, "照片返回的结果" + result);
                        try {
                            JSONObject object = new JSONObject(result);
                            String success = object.getString("Success");
                            if ("Fail".equals(success)) {
                                //表示失败
                            } else if ("Success".equals(success)) {
                                //表示成功
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        startActivity(new Intent(this, WalletActivity.class));
        finish();
        return super.onKeyDown(keyCode, event);
    }
}
